package project.dade.cn.bst.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.http.OkHeaders;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import Decoder.BASE64Encoder;
import butterknife.InjectView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import dmax.dialog.SpotsDialog;
import project.dade.cn.bst.MainActivity;
import project.dade.cn.bst.R;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.manager.AppApplication;
import project.dade.cn.bst.manager.AppConfig;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.model.LoginRequestModel;
import project.dade.cn.bst.network.FormatRequest;
import project.dade.cn.bst.utils.AESUse;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.Shn1;
import project.dade.cn.bst.utils.ToastUtil;
import project.dade.cn.bst.utils.ValidateUtil;
import project.dade.cn.bst.views.ClearEditText;

/**
 * Created by vain zhou on 2015/11/24.
 */
public class LoginActivity extends ZJPBaseBarActivity implements View.OnClickListener {
    @InjectView(R.id.universal_toolBar)
    TextView sign;
    @InjectView(R.id.accountEt)
    ClearEditText phone;
    @InjectView(R.id.passEt)
    ClearEditText password;
    @InjectView(R.id.forget_pass)
    AppCompatTextView forgetPass;
    @InjectView(R.id.loginBtn)
    AppCompatButton loginBtn;
    private ExitBroadcastReceiver receiver = new ExitBroadcastReceiver();
    public Handler mDelivery;
    String code="";


    public class ExitBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && AppConfig.ACTION_REG_SUCESS_FINISH.equals(intent.getAction())) {
                LogUtil.i(TAG, "退出登录页面");
                finish();
            }
        }

    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initData();
        initSetListener();

    }

    private void initData() {
        //注册退出广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(AppConfig.ACTION_REG_SUCESS_FINISH);
        registerReceiver(receiver, filter);
        forgetPass.setText(Html.fromHtml("<u>" + "找回密码?" + "</u>"));
    }

    private void initSetListener() {
        loginBtn.setOnClickListener(this);
        sign.setOnClickListener(this);
        forgetPass.setOnClickListener(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginBtn:
                AppUtil.closeSoftInput(this);
                //数据验证
                if (isCheckInput()) {
                    if (AppUtil.isNetworkAvailable(LoginActivity.this)) {
                        try {
                           code=AESUse.getInstance().encrypt(password.getText().toString().trim());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        requestLogin();
                    } else {
                        ToastUtil.showShort(LoginActivity.this, R.string.tips_network_error);

                    }
                }
                break;
            case R.id.universal_toolBar:
                startActivity(new Intent(LoginActivity.this, RegActivity.class));
                this.finish();
                break;
            case R.id.forget_pass:
                startActivity(new Intent(LoginActivity.this, FindPassActivity.class));
                this.finish();
                break;
        }
    }

    private void requestLogin() {
        mSpDialog = new SpotsDialog(LoginActivity.this);
        mSpDialog.show();
        HashMap<String,String > hashMap = new HashMap<String,String>();
        hashMap.put("MobilePhone",phone.getText().toString().trim());
        hashMap.put("PassWord", code);
        RequestBody body = new FormEncodingBuilder()
                .add("MobilePhone", phone.getText().toString().trim())
                .add("PassWord", code)
                .add("Sign", FormatRequest.main(hashMap))
                .build();

        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder().
                url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.login)
                .post(body)
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                mSpDialog.dismiss();
                Message msg = new Message();
                msg.what = 1;
                handler.sendMessage(msg);

                LogUtil.i(TAG, "登录请求异常：");


            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = response.body().string();
                    handler.sendMessage(msg);
                }
            }
        });

    }

    public Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    mSpDialog.dismiss();
                    String json = (String) msg.obj;
                    LogUtil.i(TAG, "获取登录用户ID：" + json);
                    if (TextUtils.isEmpty(NetRequestUtil.requestsError(json, "登录"))) {
                        BaseRequestsModel model = JSON.parseObject(json, BaseRequestsModel.class);
                        //获取请求成功
                        LoginRequestModel loginRequestInfo = JSON.parseObject(model.getData(), LoginRequestModel.class);
                        //设置登录状态
                        AppApplication.getInstance().getSpUtil().setLogin(true);
                        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS,loginRequestInfo.getUID()+""));
                        //存储相关用户基础信息
                        AppApplication.getInstance().getSpUtil().setUserID(loginRequestInfo.getUID());
                        AppApplication.getInstance().getSpUtil().setUSER_mobile(loginRequestInfo.getUserId());
                        AppApplication.getInstance().getSpUtil().setID_Cloth(loginRequestInfo.getClothesId());
                        AppApplication.getInstance().getSpUtil().setID_Car(loginRequestInfo.getCarId());
                        LogUtil.i(TAG, "获取登录用户ID：" + loginRequestInfo.getUID());
                        LogUtil.i(TAG, "获取登录用户ID：" + loginRequestInfo.getUserId());
                        ToastUtil.showShort(LoginActivity.this, "登录成功");
                        LoginActivity.this.finish();

                    } else {
                        ToastUtil.showShort(LoginActivity.this, NetRequestUtil.requestsError(json, "登录"));
                    }
                    break;
                case 1:
                    ToastUtil.showShort(LoginActivity.this, "网络相应失败请稍后再试");

            }
        }


    };


    private static final int MSG_SET_ALIAS = 1001;
    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
//                    logs = "Set tag and alias success";
//                    Log.i(TAG, logs);
                    break;
                default:
//                    logs = "Failed with errorCode = " + code;
//                    Log.e(TAG, logs);
            }

//            ExampleUtil.showToast(logs, getApplicationContext());
        }

    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
//                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
//                    Log.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
//                        Log.i(TAG, "No network");
                    }
                    break;

                default:
//                    logs = "Failed with errorCode = " + code;
//                    Log.e(TAG, logs);
            }

//            ExampleUtil.showToast(logs, getApplicationContext());
        }

    };
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };



    private boolean isCheckInput() {

        //账号不能为空
        if (TextUtils.isEmpty(phone.getText().toString().trim())) {
            ToastUtil.showShort(this, R.string.tips_phone_right);
            YoYo.with(Techniques.Shake)
                    .playOn(findViewById(R.id.accountEt));
            return false;
        }
        //验证手机号码
        if (!ValidateUtil.isMobile(phone.getText().toString().trim())) {
            ToastUtil.showShort(this, R.string.tips_phone_right);
            YoYo.with(Techniques.Shake)
                    .playOn(findViewById(R.id.accountEt));
            return false;
        }
        //密码不能为空
        if (TextUtils.isEmpty(password.getText().toString().trim())) {
            ToastUtil.showShort(this, R.string.tips_password_error);
            YoYo.with(Techniques.Shake)
                    .playOn(findViewById(R.id.passEt));
            return false;
        }
        return true;
    }

    /**
     * 跳转相关页功能
     *
     * @param <T>
     */
    private <T> void redirectToPage(Class<T> class1) {

        startActivity(new Intent(this, class1));

    }
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();

            return true;
        }

        return super.onOptionsItemSelected(item);
    }



}
